package com.gitee.mrj.aiboot.core.sf.generators.ui.widget;

import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.gitee.mrj.aiboot.annotation.config.sf.ui.widget.SFUploadWidget;
import com.gitee.mrj.aiboot.core.sf.generators.FormDefinitionGenerator;
import com.gitee.mrj.aiboot.core.sf.generators.UIForm;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Component
public class SFUploadWidgetGenerator implements FormDefinitionGenerator {
    @Override
    public void generate(UIForm root, Field field, UIForm node) {
        SFUploadWidget widget = AnnotatedElementUtils.findMergedAnnotation(field, SFUploadWidget.class);
        generate(node, widget);
    }

    private void generate(UIForm node, SFUploadWidget widget) {
        ObjectNode ui = node.getUi();
        ui.put("widget", "upload");
        putString(ui, "type", widget.type().name());
        putString(ui, "text", widget.text());
        putString(ui, "hint", widget.hint());
        putString(ui, "resReName", widget.resReName());
        putString(ui, "urlReName", widget.urlReName());
        putString(ui, "action", widget.action());
        if (ArrayUtils.isNotEmpty(widget.accept())) {
            ArrayNode array = putArray(ui, "accept");
            for (String accept : widget.accept()) {
                array.add(accept);
            }
        }
        putInt(ui, "limit", widget.limit());
        putInt(ui, "limitFileCount", widget.limitFileCount());
        putInt(ui, "fileSize", widget.fileSize());
        putString(ui, "fileType", widget.fileType());
        ui.put("listType", widget.listType().name());
        ui.put("showUploadList", widget.showUploadList());
        ui.put("multiple", widget.multiple());
        ui.put("name", widget.name());
        ui.put("withCredentials", widget.withCredentials());
        ui.put("directory", widget.directory());
        ui.put("openFileDialogOnClick", widget.openFileDialogOnClick());

    }

    @Override
    public Class[] supports() {
        return new Class[]{SFUploadWidget.class};
    }
}
